package cn.bdqn.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request){
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = sdf.format(new Date());
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        File file = new File(realPath+format);
        if (!file.isDirectory()){
            file.mkdirs();//创建父级文件路径
        }
        try {
            //file.createNewFile();//创建文件
            uploadFile.transferTo(new File(file,newName));
            String filePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+
                    "/uploadFile/"+format+newName;
            return filePath;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "上传失败";

    }


    @PostMapping("/uploads")
    public String uploads(MultipartFile[] uploadFiles, HttpServletRequest request){
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = sdf.format(new Date());
        File file = new File(realPath+format);
        if (!file.isDirectory()){
            file.mkdirs();
        }
        Map map = new HashMap();
        for (int i=0;i<uploadFiles.length;i++){
            String oldName = uploadFiles[i].getOriginalFilename();
            String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
            try {
                uploadFiles[i].transferTo(new File(file,newName));
                String filePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+
                        "/uploadFile/"+format+"/"+newName;
                map.put(i,filePath);
            }catch (Exception e){
                e.printStackTrace();
                return "上传失败";
            }
        }
        return map.toString();
    }
}
